package com.easy.controller;

import com.easy.bean.PurchaseRequest;
import com.easy.service.PurchaseRequestService;
import com.easy.util.Page;
import com.easy.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
@RequestMapping("/api/purchase_request")
public class PurchaseRequestController {

    @Autowired
    PurchaseRequestService purchaseRequestService;

    // 新增采购申请
    @PostMapping
    public Result add(@RequestBody PurchaseRequest request) {
        try {
            return Result.success(purchaseRequestService.add(request));
        } catch (IllegalArgumentException e) {
            return Result.fail(400, e.getMessage());
        } catch (DataIntegrityViolationException e) {
            return Result.fail(400, "数据完整性约束违反: " + e.getMessage());
        }
    }

    // 编辑采购申请
    @PutMapping("/{id}")
    public Result edit(@PathVariable("id") Integer id, @RequestBody PurchaseRequest request) {
        request.setId(id);
        try {
            return Result.success(purchaseRequestService.edit(request));
        } catch (DataIntegrityViolationException e) {
            return Result.fail(400, "数据完整性约束违反: " + e.getMessage());
        }
    }

    // 删除采购申请
    @DeleteMapping("/{id}")
    public Result del(@PathVariable("id") Integer id) {
        return Result.success("删除数据", purchaseRequestService.del(id));
    }

    // 查询所有采购申请（可模糊查询）
    @GetMapping
    public Result all(
            @RequestParam(name = "material_id", required = false) Integer materialId,
            @RequestParam(name = "requester_id", required = false) Integer requesterId
    ) {
        return Result.success(purchaseRequestService.all(materialId, requesterId));
    }

    // 查询单个采购申请
    @GetMapping("/{id}")
    public Result one(@PathVariable("id") Integer id) {
        return Result.success(purchaseRequestService.one(id));
    }

    // 分页查询采购申请
    @GetMapping("page")
    public Result page(Page page, PurchaseRequest request){
        purchaseRequestService.page(page, request);
        return Result.success(page);
    }
    
    @ExceptionHandler(IllegalArgumentException.class)
    public Result handleIllegalArgumentException(IllegalArgumentException e) {
        return Result.fail(400, e.getMessage());
    }
}